<template>
  <div class="app-container">
    <el-card class="search-card" shadow="never">
      <!-- 搜索操作 -->
      <template #header>
        <div class="card-header">
          <span>筛选条件</span>
          <el-button
            class="collapse-btn"
            type="text"
            @click="toggleSearch"
            :icon="showSearch ? 'ArrowDownBold' : 'ArrowUpBold'"
          >
            {{ showSearch ? "收起" : "展开" }}
          </el-button>
        </div>
      </template>

      <!-- 查询表单 -->
      <el-form
        :model="queryParams"
        ref="gradeUpdateRef"
        :inline="true"
        v-show="showSearch"
        label-width="88px"
      >
        <!-- <el-form-item label="当前等级" prop="gradeId">
          <el-input
            v-model="queryParams.gradeId"
            placeholder="请输入所属等级ID"
            clearable
            @keyup.enter="handleQuery"
          />
        </el-form-item> -->

        <!-- <el-form-item label="目标等级" prop="targetGradeId">
          <el-input
            v-model="queryParams.targetGradeId"
            placeholder="请输入目标等级ID"
            clearable
            @keyup.enter="handleQuery"
          />
        </el-form-item> -->

        <!-- <el-form-item label="单笔订单金额要求" prop="singleOrderAmount">
          <el-input
            v-model="queryParams.singleOrderAmount"
            placeholder="请输入单笔订单金额要求"
            clearable
            @keyup.enter="handleQuery"
          />
        </el-form-item> -->

        <!-- <el-form-item label="累计订单金额要求" prop="cumulativeOrderAmount">
          <el-input
            v-model="queryParams.cumulativeOrderAmount"
            placeholder="请输入累计订单金额要求"
            clearable
            @keyup.enter="handleQuery"
          />
        </el-form-item> -->

        <!-- <el-form-item label="累计订单次数要求" prop="cumulativeOrderTimes">
          <el-input
            v-model="queryParams.cumulativeOrderTimes"
            placeholder="请输入累计订单次数要求"
            clearable
            @keyup.enter="handleQuery"
          />
        </el-form-item> -->

        <!-- <el-form-item label="累计返佣金额要求" prop="cumulativeRebateAmount">
          <el-input
            v-model="queryParams.cumulativeRebateAmount"
            placeholder="请输入累计返佣金额要求"
            clearable
            @keyup.enter="handleQuery"
          />
        </el-form-item> -->

        <!-- <el-form-item label="条件有效天数" prop="validTimeDays">
          <el-input
            v-model="queryParams.validTimeDays"
            placeholder="请输入条件有效天数"
            clearable
            @keyup.enter="handleQuery"
          />
        </el-form-item> -->

        <!-- <el-form-item label="条件优先级" prop="sortOrder">
          <el-input
            v-model="queryParams.sortOrder"
            placeholder="请输入条件优先级"
            clearable
            @keyup.enter="handleQuery"
          />
        </el-form-item> -->

        <el-form-item label="状态" prop="status">
          <el-select
            v-model="queryParams.status"
            placeholder="请选择状态"
            clearable
          >
            <el-option
              v-for="dict in wdm_status"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
            />
          </el-select>
        </el-form-item>

        <!-- <el-form-item label="版本号" prop="version">
          <el-input
            v-model="queryParams.version"
            placeholder="请输入版本号"
            clearable
            @keyup.enter="handleQuery"
          />
        </el-form-item> -->

        <el-form-item>
          <el-button type="primary" icon="Search" @click="handleQuery"
            >搜索</el-button
          >
          <el-button icon="Refresh" @click="resetQuery">重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 操作按钮组 -->
    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="Plus"
          @click="handleAdd"
          v-hasPermi="['ruoyi:gradeUpdate:add']"
          >新增</el-button
        >
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="Edit"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['ruoyi:gradeUpdate:edit']"
          >修改</el-button
        >
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="Delete"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['ruoyi:gradeUpdate:remove']"
          >删除</el-button
        >
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="Download"
          @click="handleExport"
          v-hasPermi="['ruoyi:gradeUpdate:export']"
          >导出</el-button
        >
      </el-col>
      <right-toolbar
        v-model:showSearch="showSearch"
        @queryTable="getList"
      ></right-toolbar>
    </el-row>

    <!-- 表单 -->
    <el-table
      v-loading="loading"
      border
      resizable
      :data="gradeUpdateList"
      @selection-change="handleSelectionChange"
    >
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="序号" type="index" min-width="60" align="center" prop="updateId" />
      <el-table-column label="当前等级" align="center" prop="gradeId" />
      <el-table-column label="目标等级" align="center" prop="targetGradeId" />
      <!-- <el-table-column
        label="单笔订单金额要求"
        min-width="150"
        align="center"
        prop="singleOrderAmount"
      />
      <el-table-column
        label="累计订单金额要求"
        align="center"
        prop="cumulativeOrderAmount"
      />
      <el-table-column
        label="累计订单次数要求"
        align="center"
        prop="cumulativeOrderTimes"
      />
      <el-table-column
        label="累计返佣金额要求"
        align="center"
        prop="cumulativeRebateAmount"
      />
      <el-table-column
        label="条件有效天数"
        align="center"
        prop="validTimeDays"
      />
      <el-table-column label="条件优先级" align="center" prop="sortOrder" /> -->

      <el-table-column label="状态" align="center" prop="status">
        <template #default="scope">
          <dict-tag :options="wdm_status" :value="scope.row.status" />
        </template>
      </el-table-column>
      <!-- <el-table-column label="版本号" align="center" prop="version" /> -->
      <el-table-column label="备注信息" align="center" prop="remark" />
      <el-table-column
        label="操作"
        min-width="150"
        align="center"
        class-name="small-padding fixed-width"
      >
        <template #default="scope">
          <el-button
            link
            type="primary"
            icon="Edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['ruoyi:gradeUpdate:edit']"
            >修改</el-button
          >
          <el-button
            link
            type="primary"
            icon="Delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['ruoyi:gradeUpdate:remove']"
            >删除</el-button
          >
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页 -->
    <pagination
      v-show="total > 0"
      :total="total"
      v-model:page="queryParams.pageNum"
      v-model:limit="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改分销等级升级条件对话框 -->
    <el-dialog :title="title" v-model="open" width="720px" append-to-body>
      <el-collapse v-model="activeCollapse">
        <!-- 基础信息组 -->
        <el-collapse-item name="basic" title="基础信息">
          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="所属等级" prop="gradeId">
                <el-select
                  v-model="form.gradeId"
                  placeholder="请选择等级"
                  style="width: 100%"
                >
                  <el-option
                    v-for="item in gradeOptions"
                    :key="item.gradeId"
                    :label="item.gradeName"
                    :value="item.gradeId"
                  />
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="目标等级" prop="targetGradeId">
                <el-select
                  v-model="form.targetGradeId"
                  placeholder="请选择目标等级"
                  style="width: 100%"
                >
                  <el-option
                    v-for="item in gradeOptions"
                    :key="item.gradeId"
                    :label="item.gradeName"
                    :value="item.gradeId"
                  />
                </el-select>
              </el-form-item>
            </el-col>
          </el-row>
        </el-collapse-item>

        <!-- 升级条件组 -->
        <el-collapse-item name="conditions" title="升级条件">
          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="单笔订单金额(元)" prop="singleOrderAmount">
                <el-input
                  v-model="form.singleOrderAmount"
                  placeholder="请输入(如:500)"
                  @input="validateAmount('singleOrderAmount')"
                />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item
                label="累计订单金额(元)"
                prop="cumulativeOrderAmount"
              >
                <el-input
                  v-model="form.cumulativeOrderAmount"
                  placeholder="请输入(如:2000)"
                  @input="validateAmount('cumulativeOrderAmount')"
                />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="累计订单次数" prop="cumulativeOrderTimes">
                <el-input
                  v-model="form.cumulativeOrderTimes"
                  placeholder="请输入(如:10)"
                  @input="validateInteger('cumulativeOrderTimes')"
                />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item
                label="累计返佣金额(元)"
                prop="cumulativeRebateAmount"
              >
                <el-input
                  v-model="form.cumulativeRebateAmount"
                  placeholder="请输入(如:100)"
                  @input="validateAmount('cumulativeRebateAmount')"
                />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="条件有效天数" prop="validTimeDays">
                <el-input
                  v-model="form.validTimeDays"
                  placeholder="请输入(如:30)"
                  @input="validateInteger('validTimeDays')"
                />
              </el-form-item>
            </el-col>
          </el-row>
        </el-collapse-item>

        <!-- 系统配置组 -->
        <el-collapse-item name="system" title="系统配置">
          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="条件优先级" prop="sortOrder">
                <el-input
                  v-model="form.sortOrder"
                  placeholder="请输入(数值越小优先级越高)"
                  @input="validateInteger('sortOrder')"
                />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="状态" prop="status">
                <el-radio-group v-model="form.status">
                  <el-radio
                    v-for="dict in wdm_status"
                    :key="dict.value"
                    :label="dict.value"
                    >{{ dict.label }}</el-radio
                  >
                </el-radio-group>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="删除标志" prop="delFlag">
                <el-radio-group v-model="form.delFlag">
                  <el-radio
                    v-for="dict in del_flag"
                    :key="dict.value"
                    :label="dict.value"
                    >{{ dict.label }}</el-radio
                  >
                </el-radio-group>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="版本号" prop="version">
                <el-input
                  v-model="form.version"
                  disabled
                  placeholder="系统自动管理"
                />
              </el-form-item>
            </el-col>
            <el-col :span="24">
              <el-form-item label="备注信息" prop="remark">
                <el-input
                  v-model="form.remark"
                  type="textarea"
                  rows="3"
                  placeholder="请输入条件说明"
                />
              </el-form-item>
            </el-col>
          </el-row>
        </el-collapse-item>
      </el-collapse>

      <template #footer>
        <div class="dialog-footer">
          <el-button @click="cancel">取 消</el-button>
          <el-button type="primary" @click="submitForm">确 定</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="GradeUpdate">
import {
  listGradeUpdate,
  getGradeUpdate,
  delGradeUpdate,
  addGradeUpdate,
  updateGradeUpdate,
} from "@/api/ruoyi/gradeUpdate";

const { proxy } = getCurrentInstance();
const { wdm_status, del_flag } = proxy.useDict("wdm_status", "del_flag");

const gradeUpdateList = ref([]);
const open = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);
const title = ref("");

const data = reactive({
  form: {},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    gradeId: null,
    targetGradeId: null,
    singleOrderAmount: null,
    cumulativeOrderAmount: null,
    cumulativeOrderTimes: null,
    cumulativeRebateAmount: null,
    validTimeDays: null,
    sortOrder: null,
    status: null,
    version: null,
  },
  rules: {
    gradeId: [
      { required: true, message: "所属等级ID不能为空", trigger: "blur" },
    ],
    targetGradeId: [
      { required: true, message: "目标等级ID不能为空", trigger: "blur" },
    ],
    singleOrderAmount: [
      { required: true, message: "单笔订单金额不能为空", trigger: "blur" },
      {
        pattern: /^\d+(\.\d{1,2})?$/,
        message: "请输入有效金额",
        trigger: "blur",
      },
    ],
    cumulativeOrderAmount: [
      { required: true, message: "累计订单金额不能为空", trigger: "blur" },
      {
        pattern: /^\d+(\.\d{1,2})?$/,
        message: "请输入有效金额",
        trigger: "blur",
      },
    ],
    cumulativeOrderTimes: [
      { required: true, message: "累计订单次数不能为空", trigger: "blur" },
      { pattern: /^[1-9]\d*$/, message: "请输入正整数", trigger: "blur" },
    ],
    cumulativeRebateAmount: [
      { required: true, message: "累计返佣金额不能为空", trigger: "blur" },
      {
        pattern: /^\d+(\.\d{1,2})?$/,
        message: "请输入有效金额",
        trigger: "blur",
      },
    ],
    validTimeDays: [
      { required: true, message: "条件有效天数不能为空", trigger: "blur" },
      { pattern: /^[1-9]\d*$/, message: "请输入正整数", trigger: "blur" },
      { validator: validateValidTimeDays, trigger: "blur" },
    ],
    sortOrder: [
      { required: true, message: "条件优先级不能为空", trigger: "blur" },
      { pattern: /^[1-9]\d*$/, message: "请输入正整数", trigger: "blur" },
    ],
  },
});

const { queryParams, form, rules } = toRefs(data);

// 新增：搜索区域折叠/展开
function toggleSearch() {
  showSearch.value = !showSearch.value;
}

// 添加响应式数据
const activeCollapse = ref(["basic", "conditions"]);

// 验证函数
// 验证单笔订单金额
function validateAmount(field) {
  return (value) => {
    if (value && !/^\d*\.?\d{0,2}$/.test(value)) {
      form.value[field] = value.match(/^\d*\.?\d{0,2}/)[0];
    }
  };
}

// 验证整数
function validateInteger(field) {
  return (value) => {
    if (value && !/^\d+$/.test(value)) {
      form.value[field] = value.replace(/\D/g, "");
    }
  };
}

// 验证条件有效天数
function validateValidTimeDays(rule, value, callback) {
  const days = parseInt(value);
  if (days < 1 || days > 365) {
    callback(new Error("有效天数应在1-365天范围内"));
  } else {
    callback();
  }
}

/** 查询分销等级升级条件列表 */
function getList() {
  loading.value = true;
  listGradeUpdate(queryParams.value).then((response) => {
    gradeUpdateList.value = response.rows;
    total.value = response.total;
    loading.value = false;
  });
}

// 取消按钮
function cancel() {
  open.value = false;
  reset();
}

// 表单重置
function reset() {
  form.value = {
    updateId: null,
    gradeId: null,
    targetGradeId: null,
    singleOrderAmount: null,
    cumulativeOrderAmount: null,
    cumulativeOrderTimes: null,
    cumulativeRebateAmount: null,
    validTimeDays: null,
    sortOrder: null,
    status: null,
    delFlag: null,
    version: null,
    createTime: null,
    updateTime: null,
    createBy: null,
    updateBy: null,
    remark: null,
  };
  proxy.resetForm("gradeUpdateRef");
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1;
  getList();
}

/** 重置按钮操作 */
function resetQuery() {
  proxy.resetForm("queryRef");
  handleQuery();
}

// 多选框选中数据
function handleSelectionChange(selection) {
  ids.value = selection.map((item) => item.updateId);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
}

/** 新增按钮操作 */
function handleAdd() {
  reset();
  open.value = true;
  title.value = "添加分销等级升级条件";
}

/** 修改按钮操作 */
function handleUpdate(row) {
  reset();
  const _updateId = row.updateId || ids.value;
  getGradeUpdate(_updateId).then((response) => {
    form.value = response.data;
    open.value = true;
    title.value = "修改分销等级升级条件";
  });
}

/** 提交按钮 */
function submitForm() {
  proxy.$refs["gradeUpdateRef"].validate((valid) => {
    if (valid) {
      if (form.value.updateId != null) {
        updateGradeUpdate(form.value).then((response) => {
          proxy.$modal.msgSuccess("修改成功");
          open.value = false;
          getList();
        });
      } else {
        addGradeUpdate(form.value).then((response) => {
          proxy.$modal.msgSuccess("新增成功");
          open.value = false;
          getList();
        });
      }
    }
  });
}

/** 删除按钮操作 */
function handleDelete(row) {
  const _updateIds = row.updateId || ids.value;
  proxy.$modal
    .confirm('是否确认删除分销等级升级条件编号为"' + _updateIds + '"的数据项？')
    .then(function () {
      return delGradeUpdate(_updateIds);
    })
    .then(() => {
      getList();
      proxy.$modal.msgSuccess("删除成功");
    })
    .catch(() => {});
}

/** 导出按钮操作 */
function handleExport() {
  proxy.download(
    "ruoyi/gradeUpdate/export",
    {
      ...queryParams.value,
    },
    `gradeUpdate_${new Date().getTime()}.xlsx`
  );
}

getList();
</script>

<style scoped>
/* 搜索卡片样式 */
.search-card {
  /* margin-bottom: 16px; */
  border-radius: 8px;
  overflow: hidden;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.05);
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  font-weight: bold;
  color: #303133;
}

.collapse-btn {
  padding: 0;
  font-size: 14px;
  color: #606266;
}
</style>
